#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Create by zhang
# Create on 2022/6/22 10:36
import json
from os import path, sep
from typing import List

from config.config import config
from domain.report.common.period_enum import PeriodEnum
from domain.report.dto.topten_dto import TopTenDTO, ShareholdingInfoDTO
from domain.report.spider.xbrl_sse.topten_spider import topten_spider
from domain.report.spider.xbrl_sse.assembler.topten_assembler import xbrl2dtos
from infrastructure.util.bean_dict_util import bean2dict


prefix_path = path.join(config.get("data", "folder"), "report")


def insert(dto:TopTenDTO) -> bool:
    if not dto or contain(dto):
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}cash_{dto.period}.json"
    with open(basic_path, "a", encoding="utf-8") as file:
        file.write(json.dumps(bean2dict(dto)))
        return True


def insert_batch(dto_list:List[TopTenDTO]) -> bool:
    if not dto_list or len(dto_list) == 0:
        return False
    for dto in dto_list:
        if not contain(dto):
            insert(dto)
    return True


def get(stock_code:str, year:int, period:PeriodEnum) -> TopTenDTO:
    def result2dto(result:dict, dto:object):
        if not result or len(result) == 0:
            return None
        dto.__dict__ = result
        for key, val in dto.__dict__.items():
            if type(val) == dict:
                dto.__dict__[key] = result2dto(val, ShareholdingInfoDTO())
        return dto
    basic_path = f"{prefix_path}{sep}{stock_code}{sep}cash_{period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            result_dict = json.loads(line)
            if result_dict["year"] == year:
                dto = TopTenDTO()
                dto = result2dto(result_dict, dto)
                return dto
    result_dict = topten_spider(stock_code, year, period)
    dto_list = xbrl2dtos(result_dict, stock_code, period)
    insert_batch(dto_list)
    for dto in dto_list:
        if dto.year == year:
            return dto
    return None


def contain(dto:TopTenDTO) -> bool:
    if not dto:
        return False
    basic_path = f"{prefix_path}{sep}{dto.stock_code}{sep}cash_{dto.period}.json"
    with open(basic_path, "r", encoding="utf-8") as file:
        line = file.readline()
        if line:
            result_dict = json.loads(line)
            if dto.stock_code == result_dict["stock_code"] and dto.period == result_dict["period"]:
                return True
    return False